import {Command, GAME_RPICE_TYPE, GAME_TYPE, GAME_STORAGE_INFO, PROP_STAUTS} from '../constant';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import Taro from '@tarojs/taro';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';

import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    async status() {
      // 或取当前状态值
      let {
        main: {isLoading},
      } = getData();
      action.commonChange('main.isLoading', !isLoading);
    },

    /**
     * state值更新
     * @param payload
     */
    async stateCommonChange(payload) {
      const {stateName, value} = payload;
      action.commonChange(stateName, value);
    },

    /**
     * 查询用户信息
     */
    async loadUserInfo(payload) {
      action.commonChange('main.userInfo', {});
      action.commonChange('main.response.loadUser', '');
      action.commonChange('main.status.loadingUser', true);

      let {data, code, message} = await api.customerBaseController.findCustomerBaseInfoForGame({});
      let userInfo: any = data || null;
      if (!userInfo) {
        userInfo = Taro.getStorageSync(GAME_STORAGE_INFO);
      }
      console.log('action.ts loadUserInfo', userInfo);
      let accountType = '';
      if (userInfo && userInfo.customerName) {
        // 判断是否是会员
        if (!userInfo.isAquamarineMember && !userInfo.isCrystalMember) {
          accountType = '';
        } else if (userInfo.isAquamarineMember && userInfo.isCrystalMember) {
          accountType = 'isAquamarineMember&isCrystalMember';
        } else {
          accountType = userInfo.isAquamarineMember ? 'isAquamarineMember' : 'isCrystalMember';
        }
      }

      userInfo = {
        ...userInfo,
        accountType,
      };

      console.log('action.ts userinFO', userInfo);

      // 查询新人保障
      action.loadUserIsNewComer({});

      action.updateUserInfo(userInfo);

      action.commonChange('main.userInfo', {
        ...userInfo,
      });
      action.commonChange('main.response.loadUser', code);
      action.commonChange('main.status.loadingUser', false);
    },

    /**
     * 更新用户信息(storage 缓存)
     */
    async updateUserInfo(userInfo) {
      let info = Taro.getStorageSync(GAME_STORAGE_INFO) || {};
      info = {
        ...info,
        ...userInfo,
      };
      Taro.setStorageSync(GAME_STORAGE_INFO, info);
    },

    /**
     * 查询商品列表
     * @param payload
     */
    async loadProductItems(payload) {
      console.log('loadProductItems', payload);

      action.commonChange('main.productItems', []);
      action.commonChange('main.response.loadProduct', '');
      action.commonChange('main.status.loadingProduct', true);

      let {data, code, message} = await api.WishBaseController.getWishProductItems(payload);
      console.log('action.ts loadProductItem res', data);

      // 编辑查询结果
      let items = [];
      if (data && data.length > 0) {
        items = data;
      }

      action.commonChange('main.productItems', items);
      action.commonChange('main.response.loadProduct', code);
      action.commonChange('main.status.loadingProduct', false);
    },

    /**
     * 查询游戏信息
     * @param payload
     */
    async loadGameInfo(payload, type) {
      action.commonChange('main.gameInfo', {});
      action.commonChange('main.nextItem', {
        info: {},
        items: [],
      });
      action.commonChange('main.currentWish', {});
      action.commonChange('main.response.loadGameInfo', '');
      action.commonChange('main.status.loadingGameInfo', true);

      let {data, code, message} = await api.CatchPlaythingController.getGameIpConfigInfo();
      console.log('actin.tsx loadGameInfo action.ts res', data);

      // 游戏基本信息
      let gameInfo = {
        customerWishVO: null,
        prizeConfigVO: null,
        advanceList: [],
        prizeConfigId: '',
        ipId: '',
        advanceStartTime: '',
      };

      // 当前许愿信息
      let currentWish = {};

      // 下期预告
      let nextItem = {
        info: {
          advanceStartTime: '',
        },
        items: [],
      };

      // 欧气攻略
      let text = data.baseConfigVO && data.baseConfigVO.detail ? data.baseConfigVO.detail : '';
      gameInfo = {
        ...data,
        text, // 欧气攻略
        gameStartTime: data.baseConfigVO && data.baseConfigVO.startTime ? data.baseConfigVO.startTime : '',
        gameEndTime: data.baseConfigVO && data.baseConfigVO.endTime ? data.baseConfigVO.endTime : '',
      };

      // 开启游戏可玩
      if (data && data.isPlay) {
        // 当前许愿信息
        if (gameInfo && gameInfo.customerWishVO) {
          currentWish = gameInfo.customerWishVO;
        }

        // 下期预告处理
        if (gameInfo && gameInfo.advanceList && gameInfo.advanceList.length > 0) {
          nextItem.info.advanceStartTime = gameInfo.advanceStartTime; // 倒计时时间

          // 如果数组超过3，则取前三
          nextItem.items =
            gameInfo.advanceList.length > 3
              ? gameInfo.advanceList.filter((i: any, index: number) => index < 3)
              : gameInfo.advanceList;
        }

        // 如果有配置id,则需要去调取许愿信息列表
        if (gameInfo && gameInfo.prizeConfigVO && gameInfo.prizeConfigVO.id) {
          gameInfo.prizeConfigId = gameInfo.prizeConfigVO.id;
          gameInfo.ipId = gameInfo.prizeConfigVO.ipId;
          // 编辑参数
          let productParams = {
            prizeConfigId: gameInfo.prizeConfigVO.id,
          };

          console.log('actin.ts loadProductItms');

          // 查询许愿信息列表
          action.loadProductItems(productParams);
        }
      }

      action.commonChange('main.gameInfo', gameInfo);
      action.commonChange('main.currentWish', currentWish);
      action.commonChange('main.nextItem', nextItem);
      action.commonChange('main.response.loadGameInfo', code);
      action.commonChange('main.status.loadingGameInfo', false);
    },

    /**
     * 许愿
     */
    async createWishItem(payload) {
      action.commonChange('main.codeMessage', '');
      action.commonChange('main.response.createWish', '');
      action.commonChange('main.status.creatingWish', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      let {data, code, message} = await api.WishBaseController.createWishItem(params);
      console.log('action.ts createWishItem res', data);

      action.commonChange('main.codeMessage', message);
      action.commonChange('main.response.createWish', code);
      action.commonChange('main.status.creatingWish', false);
    },

    /**
     * 取消许愿
     */
    async cancelWishItem(payload) {
      console.log('actin.ts cancelWishItem payload', payload);
      action.commonChange('main.codeMessage', '');
      action.commonChange('main.response.cancelWish', '');
      action.commonChange('main.status.cancelingWish', true);

      let {data, code, message} = await api.WishBaseController.cancelWishItem(payload);
      console.log('action.ts cancelWishItem res', data);

      action.commonChange('main.codeMessage', message);
      action.commonChange('main.response.cancelWish', code);
      action.commonChange('main.status.cancelingWish', false);
    },

    /**
     * 查询新人保障
     */
    async loadUserIsNewComer(payload) {
      action.commonChange('main.response.isNewComer', '');
      action.commonChange('main.status.loadingIsNewComer', true);

      // 编辑参数
      let params = {
        ...payload,
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.CatchPlaythingController.userIsNewComer(params);
      console.log('action.ts loadUserIsNewComer data', data);

      let {
        main: {userInfo},
      } = getData();

      userInfo = {
        ...userInfo,
        isNewComer: data,
      };

      console.log('action.ts userinFO', userInfo);

      action.commonChange('main.userInfo', userInfo);
      action.commonChange('main.response.isNewComer', code);
      action.commonChange('main.status.loadingIsNewComer', false);
    },

    /**
     * 批量领取奖励 （针对抓娃娃结果页领取奖励的跳转）
     */
    async claimRewards(payload) {
      action.commonChange('main.response.claimRewards', '');
      action.commonChange('main.status.claimingRewards', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      // 编辑参数
      let {data, code, message} = await api.CatchPlaythingController.claimRewards(params);
      console.log('action.ts loadGameLottery res', data);

      action.commonChange('main.response.claimRewards', code);
      action.commonChange('main.status.claimingRewards', false);
    },

    /**
     * 奖品抽奖
     */
    async gameLottery(payload) {
      action.commonChange('main.codeMessage', '');
      action.commonChange('main.gameLotteries', []);
      action.commonChange('main.response.loadGameLottery', '');
      action.commonChange('main.status.loadingGameLottery', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      // 编辑参数
      let {data, code, message} = await api.CatchPlaythingController.drawLottery(params);
      console.log('action.ts gameLottery res', data);

      // 统计信息 （商品平铺，安慰奖统计）
      data = data || [];
      let result = data.filter(
        (i) =>
          i.prizeType != null &&
          i.prizeType != GAME_RPICE_TYPE['ticket'] &&
          i.prizeType != GAME_RPICE_TYPE['gold'] &&
          i.prizeType != GAME_RPICE_TYPE['prop'],
      );

      if (data && data.length > 0) {
        // 商品
        // let productItems = data.filter((i) => i.prizeType == GAME_RPICE_TYPE['product']);
        // if (productItems.length > 0) {
        //   let collectionIds = [];
        //   productItems.map((i) => {
        //     collectionIds.push(i.collectionId);
        //   });
        //   result.push({
        //     id: productItems.length,
        //     prizeType: GAME_RPICE_TYPE['product'],
        //     count: productItems.length,
        //     collectionIds,
        //   });
        // }

        // 优惠券筛选
        let tickItems = data.filter((i) => i.prizeType == GAME_RPICE_TYPE['ticket']);
        if (tickItems.length > 0) {
          result.push({
            id: tickItems.length,
            prizeType: GAME_RPICE_TYPE['ticket'],
            count: tickItems.length,
          });
        }

        // 道具
        let propItems = data.filter((i) => i.prizeType == GAME_RPICE_TYPE['prop']);
        if (propItems.length > 0) {
          result.push({
            id: propItems.length,
            prizeType: GAME_RPICE_TYPE['prop'],
            count: propItems.length,
          });
        }

        // 金币筛选
        let goldItems = data.filter((i) => i.prizeType == GAME_RPICE_TYPE['gold']);
        let goldNum = goldItems.reduce((goldNum, currentItem) => {
          currentItem.magicCoin = currentItem.magicCoin || 0;
          return goldNum + currentItem.magicCoin;
        }, 0);

        if (goldItems.length > 0) {
          result.push({
            id: result.length + 1,
            prizeType: GAME_RPICE_TYPE['gold'],
            count: goldNum,
          });
        }
      }
      console.log('action.ts1111 result', result);
      // 获取商品信息
      action.commonChange('main.codeMessage', message);
      action.commonChange('main.gameLotteries', result);
      action.commonChange('main.response.loadGameLottery', code);
      action.commonChange('main.status.loadingGameLottery', false);
    },

    /**
     * 查询任务列表
     */
    async loadTaskItems(payload) {
      action.commonChange('main.response.loadTask', '');
      action.commonChange('main.status.loadingTask', true);

      // 编辑参数
      let params = {
        ...payload,
        gameType: GAME_TYPE, // 暂时
      };

      let {data, code, message} = await api.GameTaskController.getTasksByGameType(params);
      console.log('loadTaskItems action data', data);

      let {
        main: {task},
      } = getData();

      action.commonChange('main.task', {
        ...task,
        items: data || [],
        page: {
          ...task.page,
        },
      });
      action.commonChange('main.response.loadTask', code);
      action.commonChange('main.status.loadingTask', false);
    },

    /**
     * 完成任务
     * @param payload
     */
    async computedTask(payload) {
      action.commonChange('main.taskType', '');
      action.commonChange('main.response.computedTask', '');
      action.commonChange('main.status.computingTask', true);

      // 编辑参数
      let params = {
        ...payload,
      };
      let {data, code, message} = await api.GameTaskController.computedTask(params);

      action.commonChange('main.taskType', payload.taskConditionsType);
      action.commonChange('main.response.computedTask', code);
      action.commonChange('main.status.computingTask', false);
    },

    /**
     * 查询任务详情
     */
    async loadTaskDetailById(payload) {
      action.commonChange('main.response.loadTaskDetail', '');
      action.commonChange('main.status.loadingTaskDetail', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      let {data, code, message} = await api.GameTaskController.getTaskDetailById(params);
      console.log('loadTaskItems action data', data);

      let {
        main: {task},
      } = getData();

      action.commonChange('main.task', {
        ...task,
        detail: {
          ...(data || {}),
        },
      });
      action.commonChange('main.response.loadTaskDetail', code);
      action.commonChange('main.status.loadingTaskDetail', false);
    },

    /**
     * 查询道具信息
     */
    async loadPropItems(payload) {
      action.commonChange('main.response.loadProp', '');
      action.commonChange('main.status.loadingProp', true);

      // 编辑参数
      let params = {
        // ...payload,
        prizeType: GAME_RPICE_TYPE['prop'],
        status: PROP_STAUTS['UNUSE'],
      };

      let {data, code, message} = await api.GamePropController.getMyProp(params);
      console.log('action.ts loadProp data', data);
      data = data || [];

      // 重组数据
      let result = [];
      if (data.length > 0) {
        data.map((i) => {
          i.propVO = i.propVO || {};
          result.push({
            ...i,
            propImg: i.propVO.imgUrl,
            propName: i.propVO.propName,
            propEndTime: i.propVO.endTime,
            propDesc: i.propVO.propDesc,
            propStartTime: i.propVO.startTime,
          });
        });
      }

      let {
        main: {prop},
      } = getData();

      action.commonChange('main.prop', {
        ...prop,
        items: result || [],
        page: {
          ...prop.page,
        },
      });
      action.commonChange('main.response.loadProp', code);
      action.commonChange('main.status.loadingProp', false);
    },

    /**
     * 判断能否使用道具
     * @param payload
     */
    async usePropPossibility(payload) {
      action.commonChange('main.codeMessage', '');
      action.commonChange('main.response.usePropPossibility', '');
      action.commonChange('main.status.usingPropPossibility', true);

      // 编辑参数
      let params = {
        ...payload,
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.GamePropController.useProp(params);
      console.log('action.ts usePropPossibility data', data);

      action.commonChange('main.response.usePropPossibility', code);
      action.commonChange('main.codeMessage', message);
      action.commonChange('main.status.usingPropPossibility', false);
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageCatchPlaythingPaMain'),
  };
}
